package utils

import (
	"time"

	"gitee.com/sansaniot/ssiot-core/logger"
	"gorm.io/datatypes"
	"gorm.io/gorm"
)

type GroupUtil struct {
}

// 分组名
func (e *GroupUtil) GroupIdName(tx *gorm.DB, deptIdQuery ...[]string) (mp map[string]string, err error) {
	mp = make(map[string]string)
	deptList := make([]Dept, 0)
	if len(deptIdQuery) > 0 {
		err = (Dept{}).FindListByConds(tx, &deptList, "dept_id in (?)", deptIdQuery[0])
	} else {
		err = (Dept{}).FindList(tx, &deptList)
	}
	if err != nil {
		logger.Error(err)
		return mp, err
	}
	for _, v := range deptList {
		mp[v.DeptId] = v.DeptName
	}
	return mp, nil
}

type Dept struct {
	DeptId        string            `json:"deptId" gorm:"primaryKey;varchar(64);comment:部门id"`
	ParentId      string            `json:"parentId" gorm:"type:varchar(64);comment:上级部门id"`
	DeptName      string            `json:"deptName" gorm:"type:varchar(100);comment:部门名称"`
	OrderNum      int32             `json:"orderNum" gorm:"type:double;comment:排序"`
	CreateTimeDts time.Time         `json:"-" gorm:"type:datetime;column:create_time;comment:创建时间"`
	CreateTime    string            `json:"createTime" gorm:"-"`
	ModifyTimeDts time.Time         `json:"-" gorm:"type:datetime;column:modify_time;comment:修改时间"`
	ModifyTime    string            `json:"modifyTime" gorm:"-"`
	CreatorId     string            `json:"creatorId" gorm:"type:varchar(64);comment:创建者id"`
	Creator       string            `json:"creator" gorm:"type:varchar(100);comment:创建者"`
	Isboot        string            `json:"isboot" gorm:"type:varchar(10);comment:是否最后一层0：否，1：是"`
	LocLongitude  float32           `json:"locLongitude" gorm:"type:double;comment:经纬度"`
	LocLatitude   float32           `json:"locLatitude" gorm:"type:double;comment:经纬度"`
	Description   string            `json:"description" gorm:"type:varchar(255);comment:描述"`
	ParentName    string            `json:"parentName" gorm:"type:varchar(100);comment:父节点名称"`
	Type          string            `json:"type" gorm:"type:varchar(10);"`
	DeptInfo      datatypes.JSONMap `json:"deptInfo" gorm:"type:longtext;comment:DeptInfo"`
	DeptExtend    string            `json:"deptExtend" gorm:"type:longtext;comment:DeptExtend"`
	Tel           string            `json:"tel" gorm:"type:varchar(20);"`
	Address       string            `json:"address" gorm:"type:varchar(255);"`
	PersonLiable  string            `json:"personLiable" gorm:"type:varchar(20);"`
}

func (Dept) FindList(db *gorm.DB, data interface{}, condition ...func(db *gorm.DB) *gorm.DB) (err error) {
	err = db.Model(&Dept{}).
		Scopes(
			condition...,
		).
		Find(data).
		Limit(-1).Offset(-1).Error
	return err
}

func (Dept) FindListByConds(db *gorm.DB, data interface{}, conds string, params ...interface{}) (err error) {
	return db.Model(&Dept{}).Where(conds, params...).Find(data).Error
}

func (Dept) TableName() string {
	return "t_dept"
}
